package DAO;

import DataBase.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import Reflect.ReflectionUtils;

import java.sql.Connection;
import java.util.ArrayList;

/**
 * ??????????CRUD???????????????????
 * @author shaohui
 * ????DBUtils???????
 *<T>  ???DAO?????????????????????
 */
public class Dao<T> {

	private Class<T>  clazz;
	private QueryRunner queryRunner=new QueryRunner();
	public Dao() {
		clazz=  ReflectionUtils.getSuperGenericType(getClass());
	}
	/**
	 * ??????????ε??
	 * @param sql
	 * @param args
	 * @return
	 */
	public  <E> E getForValue(String  sql, Object...args) {
		Connection connection=null;
		try {
			connection=JdbcUtils.getConnection();
            return (E) queryRunner.query(connection, sql, new ScalarHandler(), args);

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtils.releaseConnection(connection);
		}
		return null;
	}
	
	/**
	 * ????T???????List
	 * @param sql
	 * @param args
	 * @return
	 */
	public ArrayList<T> getForArrayList(String sql, Object...args){
		Connection connection=null;
		try {
			connection=JdbcUtils.getConnection();
            return (ArrayList<T>)queryRunner.query(connection, sql, new BeanListHandler<>(clazz), args);

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally {
			JdbcUtils.releaseConnection(connection);
		}
	}
	
	/**
	 * ????????T??????????????????
	 * @param sql
	 * @param args
	 * @return
	 */
	public T getForArray(String sql, Object...args) {
		Connection connection=null;
		try {
			connection=JdbcUtils.getConnection();
            return queryRunner.query(connection, sql, new BeanHandler<>(clazz), args);

		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtils.releaseConnection(connection);
		}
		return null;
	}
	
	/**
	 * ?????insert,delete,update????
	 * @param sql  SQL???
	 * @param args ???SQL????е??λ????????
	 */
	public void update(String sql,  Object...args) {
		Connection connection=null;
		try {
			connection=JdbcUtils.getConnection();
			queryRunner.update(connection,sql, args);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtils.releaseConnection(connection);
		}
	}

}
